package com.eliaukjq.xunlianying.duoxianchengjichu;

import java.lang.ref.WeakReference;

/**
 * @Author : 佩萁
 * Description :
 * @Create : 2024/7/20 - 21:59
 */
public class WeakReferenceExample  {
    public static void main(String[] args) {
        MyClass myObject = new MyClass();
        WeakReference<MyClass> weakRef = new WeakReference<>(myObject);

        myObject = null; // 取消强引用

        // 尝试获取弱引用对象
        if (weakRef.get() != null) {
            System.out.println("Object is still alive.");
        } else {
            System.out.println("Object has been garbage collected.");
        }

        // 强制垃圾回收
        System.gc();

        // 尝试获取弱引用对象
        if (weakRef.get() != null) {
            System.out.println("Object is still alive.");
        } else {
            System.out.println("Object has been garbage collected.");
        }
    }
}
class MyClass {
    // 类的定义
}